﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Cocbook_DTO;
using Cocbook_DAL;
using System.Diagnostics;

namespace Cocbook_checker
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        public static Project project;
        public ProjectDAL projectDAL = new ProjectDAL();
        public Book curentBook = new Book();
        public BookDAL bookDAL = new BookDAL();
        public Project_BookDAL pbDAL = new Project_BookDAL();
        public Project_Book project_bookEdit = null;
        public List<Project_Book> lpb = new List<Project_Book>();
        public int editingRow = 0;
        public int addRow = -1;
        public static Int64 IsBn = 0;
        public Connection con = new Connection();
        public bool save = false;

        public void Add()
        {

            txtDiscount.Clear();
            txtBookTitle.Clear();
            txtBookID.Clear();
            txtBookID.Focus();
        }

        public void Search()
        { 
        
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            switch (keyData)
            {
                case Keys.Escape:
                    txtBookID.Clear();
                    txtCopy.Clear();
                    txtDiscount.Clear();
                    break;

                case Keys.F1:
                    btnSearchByName_Click(null, null);
                    break;
            }
            return base.ProcessDialogKey(keyData);
        }


        private void btnClear_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có muốn xóa hết dữ liệu trên bảng không?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (MessageBox.Show("Toàn bộ sách đang có trong danh sách sẽ bị xóa khỏi cơ sở dữ liệu. Bạn có chắc muốn xóa hết hay không?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    dgvList.Rows.Clear();
                    foreach (Project_Book pb in lpb)
                    {
                        (new Project_BookDAL()).DeleteProject_Book(pb.Project.ProjectID, pb.Book.BookID);
                    }
                    ResetInput();
                }
            }
        }
        

        private void Form1_Load(object sender, EventArgs e)
        {
            if (con.CheckConnection())
            {
                cbxTableID.Items.Clear();
                sbtConnectStatus.Value = true;
                project = projectDAL.GetProjectByStatus();
                lblProjectName.Text = project.ProjectName;
                for (int i = 1; i <= project.Table; i++)
                {
                    cbxTableID.Items.Add(i.ToString());
                }
                cbxTableID.Enabled = true;
            }
            else
            {
                sbtConnectStatus.Value = false;
                cbxTableID.Enabled = false;
            }
        }

        private void cbxTableID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtBookID.Enabled = true;
            txtCopy.Enabled = true;
            txtDiscount.Enabled = true;
            btnAddBook.Enabled = true;
            btnClear.Enabled = true;
            btnSearchByName.Enabled = true;
            txtBookID.Focus();
        }

        private void frmMain_Resize(object sender, EventArgs e)
        {
            dgvList.Columns[3].Width = 450 + dgvList.Size.Width - 1154;
        }

        private void txtBookID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        public bool CheckISBN()
        {
            if (txtBookID.TextLength >= 10 && txtBookID.TextLength <= 13)
            {
                return true;
            }
            else
            {
                txtBookID.Clear();
                txtBookID.Focus();
                highlighter1.SetHighlightColor(txtBookID, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                lblValidate.Text = "Mã ISBN sai";
                return false;
            }
        }

        public int FindBookIndex(Int64 isbn)
        {
            int result = -1;
            for (int i = 0; i < dgvList.Rows.Count; i++)
            {
                if (Convert.ToInt64(dgvList[2, i].Value) == isbn)
                {
                    result = i;
                    break;
                }
            }
            return result;
        }

        public void LoadBook()
        {
            Book book = bookDAL.GetBookByISBN(Convert.ToInt64(txtBookID.Text));
            if (book == null)
            {
                txtBookID.Clear();
                highlighter1.SetHighlightColor(txtBookID, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                lblValidate.Text = "Mã vạch sai. Vui lòng nhập lại.";
                txtBookID.Focus();
            }
            else
            {
                try
                {
                    Project_Book pro_book = new Project_Book();
                    pro_book = new Project_Book();
                    pro_book = pbDAL.GetProject_BookByID(project.ProjectID, book.BookID);
                    if (pro_book == null)
                    {
                        int i = FindBookIndex(book.ISBN);
                        if (i == -1)
                        {
                            curentBook = book;
                            txtBookTitle.Text = book.Title;
                            txtCopy.Focus();
                            txtCopy.SelectAll();
                        }
                        else
                        {
                            if (Convert.ToInt16(dgvList[1, i].Value) == cbxTableID.SelectedIndex + 1)
                            {
                                addRow = i;
                                txtBookTitle.Text = dgvList[3, i].Value.ToString();
                                txtCopy.Focus();
                                txtDiscount.Text = dgvList[8, i].Value.ToString();
                            }
                            else
                            {
                                txtBookID.Clear();
                                highlighter1.SetHighlightColor(txtBookID, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                                lblValidate.Text = "Mã vạch này đã được nhập tại bàn " + dgvList[1, i].Value.ToString() + ". Bạn phải đổi mã bàn trước.";
                                ResetInput();
                            }
                        }
                    }
                    else
                    {
                        if (pro_book.TableNumber == cbxTableID.SelectedIndex + 1)
                        {
                            int i = FindBookIndex(book.ISBN);
                            if (i == -1)
                            {
                                project_bookEdit = pro_book;
                                curentBook = book;
                                txtBookTitle.Text = book.Title;
                                txtCopy.Text = pro_book.Copy.ToString();
                                txtDiscount.Text = pro_book.Discount.ToString();
                                txtCopy.Focus();
                                txtCopy.SelectAll();
                            }
                            else
                            {
                                if (Convert.ToInt16(dgvList[1, i].Value) == cbxTableID.SelectedIndex + 1)
                                {
                                    project_bookEdit = pro_book;
                                    addRow = i;
                                    txtBookTitle.Text = dgvList[3, i].Value.ToString();
                                    txtCopy.Focus();
                                    txtDiscount.Text = dgvList[8, i].Value.ToString();
                                }
                                else
                                {
                                    txtBookID.Focus();
                                    txtBookID.SelectAll();
                                    highlighter1.SetHighlightColor(txtBookID, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                                    lblValidate.Text = "Mã vạch này đã được nhập tại bàn " + dgvList[1, i].Value.ToString() + ". Bạn phải đổi mã bàn trước.";
                                    txtBookTitle.Clear();
                                    txtCopy.Clear();
                                    txtDiscount.Clear();
                                }
                            }
                        }
                        else
                        {
                            txtBookID.Focus();
                            txtBookID.SelectAll();
                            highlighter1.SetHighlightColor(txtBookID, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                            lblValidate.Text = "Mã vạch này đã được nhập tại bàn " + pro_book.TableNumber + ". Bạn phải đổi mã bàn trước.";
                            txtBookTitle.Clear();
                            txtCopy.Clear();
                            txtDiscount.Clear();
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("Mất kết nối với máy chủ");
                }
            }
        }

        private void txtBookID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (CheckISBN())
                {
                    LoadBook();
                }
            }
        }

        #region Clear Validate

        private void txtBookID_TextChanged(object sender, EventArgs e)
        {
            txtBookTitle.Clear();
            highlighter1.SetHighlightColor(txtBookID, DevComponents.DotNetBar.Validator.eHighlightColor.None);
            lblValidate.Text = "";
        }

        private void txtCopy_TextChanged(object sender, EventArgs e)
        {
            highlighter1.SetHighlightColor(txtCopy, DevComponents.DotNetBar.Validator.eHighlightColor.None);
            lblValidate.Text = "";
        }

        private void txtDiscount_TextChanged(object sender, EventArgs e)
        {
            highlighter1.SetHighlightColor(txtCopy, DevComponents.DotNetBar.Validator.eHighlightColor.None);
            lblValidate.Text = "";
        }

        #endregion

        private void txtCopy_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void txtCopy_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (txtCopy.Text == "" || int.Parse(txtCopy.Text) == 0)
                {
                    txtCopy.Clear();
                    highlighter1.SetHighlightColor(txtCopy, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                    lblValidate.Text = "Số lượng nhập không được bằng 0";
                    txtCopy.Focus();
                }
                else
                {
                    txtDiscount.Focus();
                    txtDiscount.SelectAll();
                }
            }
            else
            {
                if (e.KeyCode == Keys.Escape)
                {
                    ResetInput();
                }
            }
        }

        private void txtDiscount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddBookToList();
            }
            else
            {
                if (e.KeyCode == Keys.Escape)
                {
                    ResetInput();
                }
            }
        }

        public void ResetInput()
        {
            txtBookID.Enabled = true;
            txtDiscount.Clear();
            txtBookTitle.Clear();
            txtCopy.Clear();
            txtBookID.Clear();
            txtBookID.Focus();
        }

        public void AddBookToList()
        {
            try
            {
                if (txtDiscount.Text == "") txtDiscount.Text = "0";
                double discount = Convert.ToDouble(txtDiscount.Text);
                if (txtBookTitle.Text == "" && txtBookID.Enabled)
                {
                    highlighter1.SetHighlightColor(txtBookID, DevComponents.DotNetBar.Validator.eHighlightColor.None);
                    lblValidate.Text = "Bạn phải xác nhận mã vạch trước. vui lòng quét lại mã vạch.";
                    txtBookID.Focus();
                }
                else
                {
                    if (txtCopy.Text == "" || txtCopy.Text.Length > 4)
                    {
                        txtCopy.Clear();
                        highlighter1.SetHighlightColor(txtCopy, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                        lblValidate.Text = "Số lượng nhập không hợp lệ";
                        txtCopy.Focus();
                    }
                    else
                    {
                        try
                        {
                            bool check = true;
                            if (txtBookID.Enabled)
                            {
                                if (addRow == -1)
                                {
                                    if (project_bookEdit != null)
                                    {
                                        check = (new Project_BookDAL()).UpdateProject_Book(new Project_Book(project, project_bookEdit.Book, Convert.ToInt16(txtCopy.Text), discount, cbxTableID.SelectedIndex + 1, false));
                                        if (check)
                                        {
                                            lpb.Add(new Project_Book(project, project_bookEdit.Book, Convert.ToInt16(txtCopy.Text), discount, cbxTableID.SelectedIndex + 1, false));
                                        }
                                    }
                                    else
                                    {
                                        Project_Book pb = new Project_Book(project, curentBook, Convert.ToInt16(txtCopy.Text), Convert.ToInt16(txtDiscount.Text), cbxTableID.SelectedIndex + 1, false);
                                        check = (new Project_BookDAL()).CreateProject_Book(pb);
                                        if (check)
                                        {
                                            lpb.Add(pb);
                                        }
                                    }
                                    if (check)
                                    {
                                        dgvList.Rows.Add(dgvList.RowCount + 1, cbxTableID.SelectedIndex + 1, curentBook.ISBN, curentBook.Title,
                                            curentBook.Publisher, curentBook.Issuer, curentBook.Price, Convert.ToInt16(txtCopy.Text), discount);
                                    }
                                }
                                else
                                {
                                    Project_Book temp = lpb[addRow];
                                    temp.Copy = Convert.ToInt16(dgvList[7, addRow].Value);
                                    temp.Discount = discount;
                                    check = (new Project_BookDAL()).UpdateProject_Book(lpb[addRow]);
                                    if (check)
                                    {
                                        dgvList[8, addRow].Value = discount;
                                        dgvList[7, addRow].Value = Convert.ToInt16(dgvList[7, addRow].Value) + Convert.ToInt16(txtCopy.Text);
                                        lpb[addRow] = temp;
                                        addRow = -1;
                                    }
                                }
                            }
                            else
                            {
                                Project_Book temp = lpb[editingRow];
                                temp.Copy = Convert.ToInt16(dgvList[7, editingRow].Value);
                                temp.Discount = discount;
                                check = (new Project_BookDAL()).UpdateProject_Book(temp);
                                if (check)
                                {
                                    dgvList[7, editingRow].Value = Convert.ToInt16(txtCopy.Text);
                                    dgvList[8, editingRow].Value = discount;
                                    lpb[editingRow] = temp;
                                }
                            }
                            if (check)
                            {
                                ResetInput();
                            }
                            else
                            {
                                "".Substring(2);
                            }
                        }
                        catch
                        {
                            MessageBox.Show("Lỗi kết nối");
                        }
                    }
                }
            }
            catch
            {
                highlighter1.SetHighlightColor(txtDiscount, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                lblValidate.Text = "Chiết khấu không hợp lệ.";
                txtDiscount.Focus();
                txtDiscount.SelectAll();
            }
        }



        private void txtDiscount_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsControl(e.KeyChar)&&!Char.IsDigit(e.KeyChar)&&!(e.KeyChar.Equals(',')&&!txtDiscount.Text.Contains(',')))
            {
                e.Handled = true;
            }
        }

        private void dgvList_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            if (!save)
            {
                for (int i = e.RowIndex + 1; i <= dgvList.RowCount; i++)
                {
                    dgvList.Rows[i - 1].Cells[0].Value = i;
                }
                (new Project_BookDAL()).DeleteProject_Book(lpb[e.RowIndex].Project.ProjectID, lpb[e.RowIndex].Book.BookID);
                lpb.RemoveAt(e.RowIndex);
                txtBookID.Focus();
            }
        }

        private void dgvList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 9)
            {
                if (MessageBox.Show("Bạn có muốn bỏ kiểm kê quyển sách này không?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    dgvList.Rows.RemoveAt(e.RowIndex);
                    txtBookID.Focus();
                }
            }
            else
            {
                txtBookID.Enabled = false;
                txtBookID.Text = dgvList[3, e.RowIndex].Value.ToString();
                txtBookTitle.Text = dgvList[4, e.RowIndex].Value.ToString();
                txtCopy.Text = dgvList[7, e.RowIndex].Value.ToString();
                txtDiscount.Text = dgvList[8, e.RowIndex].Value.ToString();
                editingRow = e.RowIndex;
                txtCopy.Focus();
                txtCopy.SelectAll();
            }
        }

        private void btnAddBook_Click_1(object sender, EventArgs e)
        {
            AddBookToList();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (dgvList.Rows.Count == 0)
            {
                MessageBox.Show("Vui lòng nhập thông tin sách trước");
                ResetInput();
            }
            else
            {
                if (con.CheckConnection())
                {
                    int i = 0;
                    Project_BookDAL pbDAL;
                    foreach (Project_Book pb in lpb)
                    {
                        pbDAL = new Project_BookDAL();
                        pb.Copy = Convert.ToInt16(dgvList[7, i].Value);
                        pb.Discount = Convert.ToInt16(dgvList[8, i].Value);
                        i = i + 1;
                        pbDAL.UpdateProject_Book(pb);
                    }
                    save = true;
                    dgvList.Rows.Clear();
                    save = false;
                    ResetInput();
                    MessageBox.Show("Hoàn tất!");
                }
                else
                {
                    MessageBox.Show("Hiện đang mất kết nối với máy chủ, vui lòng thử lại");
                }
            }
        }

        

        private void btnSearchByName_Click(object sender, EventArgs e)
        {
            frmSearch frm = new frmSearch();
            frm.ShowDialog();
            if (IsBn != 0)
            {
                txtBookID.Text = IsBn.ToString();
                LoadBook();
                IsBn = 0;
            }
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            frmSetupServer frm = new frmSetupServer();
            frm.ShowDialog();
        }

        private void buttonX2_Click(object sender, EventArgs e)
        {
            Form1_Load(null, null);
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("Bạn có muốn thoát hẵn chương trình hay không?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                e.Cancel = true;
            }
        }

        private void buttonX3_Click(object sender, EventArgs e)
        {
            Process.Start("log.txt");
        }

        

    }

















}
